<template>
  <el-dialog title="编辑"  :close-on-click-modal="false" :visible.sync="show" class="dialog_index"
   :before-close="cancle">
    <el-form   label="right" :rules="rules" :model="form" ref="addSiteFrom" >
      <el-form-item label="图片：" prop="image" class="menuIcon">
        <el-upload class="uploadSocialMediaIcon" :action="actionUrl" 
          :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, item)"
            :on-error="handleError" :before-upload="beforeUpload"
          :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type:'social_media', imageheight: imgH, imagewidth: imgW}" >
            <br><el-button size="small" type="primary" @click.stop="closeDrawerDialog">图库选择</el-button> 
            <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
          </el-upload>
          <el-image :src="utils.setCdnUrl()  + form.image" v-show="form.image"></el-image>
          <p class="upload__tip">建议上传.jpg/.jpeg/.png格式，且尺寸比例为1:1，大小≤1M，每次只能上传一个</p>
      </el-form-item>
      <el-form-item label="账号：" prop="account">
        <el-input v-model="form.account" placeholder="账号（必填项）"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" @click="submitForm">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
    <Drawer v-show="showDrawer" :type="'social_media'" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>

  </el-dialog>
  
</template>

<script>
import Drawer  from '@/components/Gallery/index.vue' 
import { editGet, editPost } from  '@/api/index/socialMedia.js'

export default {
  props: {
    show: Boolean,
    closeAddDialog:Function,
    id: Number
  },
  components: { Drawer },
  data() {
    return {
      showDrawer: false,
      form:{
        image: "",
        account: ''
      },
      // 字段xx为必填项！
      rules:{
        account:[
          { required: true, message: '字段账号为必填项', trigger: 'change' },
            { min: 1, max: 50, message: '账号最多50字符', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '图片为必填项', trigger: 'blur' },
        ]

      },
      actionUrl: "/api/api/general/upload",
      imgW: '',
      imgH: ''
    }
  },
  watch: {
   show: function(){
      if (this.show) {
        this.getEdit()
      }
    }
  },

	
  methods:{
    getEdit(){
      this.loading = true
      let params = {
        id: this.id
      }
      editGet(params).then(res=>{
        if(res.state == 1) {
          let data  = res.data
          this.form = data
        } else {
          this.$message.error(res.message)
        }
          this.loading = false
      })
    },
    postEdit(){
      editPost(this.form).then(res=>{
        if(res.state == 1){
        this.$message.success('保存站点信息' +res.message)
        this.cancle()
        }
      })
    },
    // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if(data && data.filePathNameHttp )  { 
        this.image = data.filePathNameHttp
        this.form.image = data.filePathName
      }
    },
    submitForm(){
      this.$refs.addSiteFrom.validate((valid) => {
        if (valid) {
          this.postEdit()
        } else {
          return false;
        }
      });
    },
    cancle(){
      this.$emit('closeDialog')
      this.$refs.addSiteFrom.clearValidate();
      this.$refs.addSiteFrom.resetFields(); // 清空原来的数据
    },
    handleSuccess(response){
      this.form.image = response.data.filePathName
      this.image = response.data.filePathNameHttp
      this.$message.success('上传图片成功')   
    },
    handleError(){
      this.$message.error('上传图标失败')   
    },
    beforeUpload(file){
      let that = this
      const isLt2M = file.size / 1024  <  1024;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过1M")
        return false
      }
      if(file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg'){
        this.$message.error("仅支持.jpg/.jpeg/png格式的图片")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = img.width ==  img.height ;
          valid ? resolve() : reject();
          that.imgW = img.width
          that.imgH = img.height
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        // that.$message.error('上传图标为正方形')
        // return Promise.reject()
        return file
      })
      return isSize
    }
  }
}
</script>

<style lang="scss">

</style>